package com.zjlp.seproject.controller;

import com.zjlp.seproject.pojo.*;
import com.zjlp.seproject.service.SubjectService;
import com.zjlp.seproject.service.UserService;
import com.zjlp.seproject.service.impl.UserServiceImpl;
import com.zjlp.seproject.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
public class HelloController {
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private UserService userService;

    /**
     *
     * @param id 课程id
     * @param authorization 用户token
     * @param response 相应
     * @return  简单的项目信息
     */
    @CrossOrigin
    @RequestMapping("/getBrifSubject")
    public List<BrifSubject> selectBrif(@RequestBody ID id,
                                        @RequestHeader("Authorization") String authorization, HttpServletResponse response) {
        System.out.println("getBrifSubject");
//        System.out.println("authorization=" + authorization);
        if (!JwtUtil.verify(authorization)) {
            response.setStatus(999);
            return null;
        }
        return subjectService.selectBrif(id.getId());
    }

    /**
     *
     * @param id  项目id
     * @return  返回SubjectDetails对象
     */
    @CrossOrigin
    @RequestMapping("/getSubjectDetails")
    public SubjectDetails getSubjectDetails(@RequestBody ID id) {
        System.out.println("getSubjectDetails");
        return subjectService.selectByPrimaryKey(id.getId());
    }

    /**
     *
     * @param user  传入用户对象
     * @param response  相应
     * @return  返回Login对象
     */
    @CrossOrigin
    @RequestMapping("/login")
    public Login login(@RequestBody User user, HttpServletResponse response) {
        System.out.println("login:" + user.getUsername());
        User u = userService.login(user);
        if (u == null) {
            response.setStatus(999);
            return null;
        } else {
            String token = JwtUtil.sign(u.getId().toString());
            return new Login(token, u.getAvatar(), u.getAdmin());
        }
    }

    /**
     *
     * @param user  传入用户对象
     */
    @CrossOrigin
    @RequestMapping("/register")
    public void register(@RequestBody User user) {
        System.out.println("register:" + user.getUsername());
        user.setAvatar("http://localhost:8443/avatar/avatar.jpg");
        userService.register(user);
    }

//    @Autowired
//    private UserServiceImpl userservice;
//
//    @RequestMapping("/hello")
//    public User hello(){
//        return userservice.selectByPrimaryKey(1);
//    }
//
//    @RequestMapping(value = "/id")
//    public User selectByID(Integer id){
//        return userservice.selectByPrimaryKey(id);
//    }
//
//    @RequestMapping(value = "/id2",method = RequestMethod.GET)
//    public String selectByID2(){
//        return "Only Get";
//    }

}